/*
 * Date：10/23/18 10:15 PM
 * Author: guomw
 *
 */

package org.elanfox.intellicommunity.biz.service.core.resident.impl;

import org.elanfox.intellicommunity.biz.dto.condition.WorkerStructureCondition;
import org.elanfox.intellicommunity.biz.entity.auth.SystemManager;
import org.elanfox.intellicommunity.biz.entity.resident.StructurePO;
import org.elanfox.intellicommunity.biz.entity.resident.WorkerStructureRelPO;
import org.elanfox.intellicommunity.biz.repository.resident.WorkerStructureRepository;
import org.elanfox.intellicommunity.biz.service.core.resident.WorkerStructureService;
import org.elanfox.intellicommunity.common.constant.Constant;
import org.elanfox.intellicommunity.data.base.base.AbstractSearchableCrudService;
import org.elanfox.intellicommunity.data.base.base.SpecificationAndSort;
import org.elanfox.intellicommunity.data.base.dto.BaseSaveDTO;
import org.elanfox.intellicommunity.data.base.dto.BaseSearchDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.Predicate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 管家楼层关联service
 *
 * @author loutianxi
 * @date 2019-12-05
 */
@Service
public class WorkerStructureServiceImpl extends AbstractSearchableCrudService<WorkerStructureRelPO, Integer> implements WorkerStructureService {

    @Autowired
    private WorkerStructureRepository repository;

    protected WorkerStructureServiceImpl(WorkerStructureRepository repository) {
        super(repository);
    }

    @Override
    protected SpecificationAndSort<WorkerStructureRelPO> specificationAndSort(BaseSearchDTO condition) {
        WorkerStructureCondition workerStructureCondition = (WorkerStructureCondition) condition;
        Specification<WorkerStructureRelPO> specification = (root, query, cb) -> {
            List<Predicate> predicates = new ArrayList<>();

            return cb.and(predicates.toArray(new Predicate[predicates.size()]));
        };
        Sort sort = new Sort(Sort.Direction.DESC, "createTime");
        return new SpecificationAndSort<>(specification, sort);
    }

    @Override
    public WorkerStructureRelPO save(BaseSaveDTO saveDTO) {
        SystemManager manager = (SystemManager) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        WorkerStructureRelPO po = (WorkerStructureRelPO) saveDTO;
        po.setCreateTime(LocalDateTime.now());
        po.setUpdateTime(LocalDateTime.now());
        po.setWorkerId(manager.getUserId());
        return repository.save(po);
    }

    @Override
    @Transactional
    public List<WorkerStructureRelPO> save(Integer userId, String structureIds) {
        SystemManager manager = (SystemManager) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        LocalDateTime now = LocalDateTime.now();
        List<WorkerStructureRelPO> list = new ArrayList<>();
        //第一步删除工作人员名下的所有楼层
        repository.deleteByWorkerId(userId);
        //第二步保存新的负责楼层
        for (String strId : structureIds.split(Constant.SPLIT)) {
            if (StringUtils.isEmpty(strId)) {
                continue;
            }
            WorkerStructureRelPO po = new WorkerStructureRelPO();
            po.setWorkerId(userId);
            po.setStructurePO(new StructurePO(Integer.parseInt(strId)));
            po.setCreateTime(now);
            po.setUpdateTime(now);
            po.setCreator(manager.getUsername());
            list.add(po);
        }
        return repository.saveAll(list);
    }

    @Override
    public String findByWorkerId(Integer workerId) {
        StringBuffer stringBuffer = new StringBuffer("|");
        List<WorkerStructureRelPO> list = repository.findByWorkerId(workerId);
        for (WorkerStructureRelPO obj : list) {
            stringBuffer.append(obj.getStructurePO().getStructureId()).append("|");
        }
        return stringBuffer.toString();
    }


}
